const router = require("koa-router")()
// const query=require("../db/query")
router.get("/api/userList", async ctx => {//查找
    try {
        let total=await ctx.mysql.query("select count(*) from userList")
        let { pagenum = 1, limit = 2} = ctx.query
        let startIndex = (pagenum - 1) * limit

        let data = await ctx.mysql.query(`select * from userList limit ${startIndex},${limit}`)//分页
        ctx.body = {
            code: 1,
            msg: data,
            total:total[0]["count(*)"]
        }

    } catch (e) {
        ctx.body = {
            code: 0,
            msg: "分页失败"
        }
    }
})

router.post("/api/add", async ctx => {//增加
    let { userName, password, phone } = ctx.request.body; //解构从前端传进来的数据
    console.log(userName, password, phone);
    
    if (!userName && !password && !phone) {//容错处理

        return ctx.body = { code: 0, msg: "参数缺失" }
    }
    let user = await ctx.mysql.query("select * from userList where phone=?", [phone])//判断一下是否重复 
    if (user.length) {//重复
        ctx.body = { code: 2, msg: "此人已存在" }
    } else {//未重复
        let data = ctx.mysql.query("insert into userList (userName,password,phone) values (?,?,?)", [userName, password, phone])//插入mysql
        console.log(data);

        ctx.body = { code: 1, msg: "添加成功" }
    }
})


router.get('/api/delect', async ctx => {//删除
    let { id } = ctx.query

    if (id || id === 0) {//容错处理
        await ctx.mysql.query("delete from userList where id=?", [id])
        ctx.body = { code: 1, msg: "删除成功" }

    } else {
        ctx.body = {
            code: 0,
            msg: "id不存在"
        }
    }

})

router.post("/api/emit", async ctx => {

    let { userName, password, phone, id } = ctx.request.body;
        console.log(id);
        
    if (!userName && !password && !phone && !id) {
        ctx.body = {
            code: 0,
            msg: "信息不完整"
        }
    }

    let data = await ctx.mysql.query("update userList set userName=?,password=?,phone=? where id=?", [userName, password, phone, id])
    ctx.body = {
        code: 1,
        msg: "修改成功"
    }
    console.log(data);
})
module.exports = router